from php4dvd.model import movie

__author__ = 'DSperansky'

from php4dvd.pages.internal_page import InternalPage
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys


class MainPage(InternalPage):

    @property
    def add_movie_button(self):
        add_movie_css_locator = "nav li:first-of-type>div.button img"
        return self.wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, add_movie_css_locator)))

    @property
    def search_input(self):
        search_input_css_locator = "div.searchbox>input#q"
        return self.wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, search_input_css_locator)))

    @property
    def results_first_child(self):
        results_first_child_css_locator = "div#results>*:first-child"
        return self.wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, results_first_child_css_locator)))

    @property
    def is_this_page(self):
        return self.is_element_visible((By.CSS_SELECTOR, "nav li:first-of-type>div.button img"))

    #Page object can have methods
    def click_movie_by_title(self, title):
        all_movie_titles_css_locator = "div#results div.title"
        lst_titles = self.wait.until(ec.presence_of_all_elements_located((By.CSS_SELECTOR, all_movie_titles_css_locator)))
        for movie_title in lst_titles:
            if title == movie_title.text:
                movie_title.click()
                return

    def get_movie_ids(self):
        all_movies_css_locator = "div#results>a>div"
        try:
            lst_movies = self.wait.until(ec.presence_of_all_elements_located((By.CSS_SELECTOR, all_movies_css_locator)))
            lst_ids = [str(film.get_attribute("id")).split('_')[1] for film in lst_movies]
        except TimeoutException, e:
            lst_ids = []
        return lst_ids

    def get_movie_id_by_title(self, title):
        lst_ids = self.get_movie_ids()
        for id in lst_ids:
            movie_with_id_css_locator = "div#results>a>div[id='movie_" + str(id) +"']"
            movie_elem = self.wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, movie_with_id_css_locator)))
            movie_title = movie_elem.find_element_by_class_name('title').text
            if title == movie_title:
                return id
        return 0

    def clear_search_input(self):
        self.search_input.clear()
        old_element = self.results_first_child
        self.search_input.send_keys(Keys.RETURN)
        self.wait.until(ec.staleness_of(old_element))

    def search(self, title):
        self.search_input.send_keys(title)
        old_element = self.results_first_child
        self.search_input.send_keys(Keys.RETURN)
        self.wait.until(ec.staleness_of(old_element))

